package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.InterventionDao;
import com.itheima.dao.KnowledgeFoodDao;
import com.itheima.dao.KnowledgeSportDao;
import com.itheima.myExceptions.AssociatedException;
import com.itheima.pojo.PhysicalExam;
import com.itheima.service.InterventionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

/**
 * 健康干预服务实现类
 */
@Service(interfaceClass = InterventionService.class)
@Transactional
public class InterventionServiceImpl implements InterventionService {
    @Autowired
    private InterventionDao interventionDao;

    @Autowired
    private KnowledgeFoodDao knowledgeFoodDao;

    @Autowired
    private KnowledgeSportDao knowledgeSportDao;


    //添加健康干预
    @Override
    public void add(PhysicalExam physicalExam, Integer[] foodIds, Integer[] sportIds) throws AssociatedException {
        //获得体检结果id
        Integer physicalExamId = physicalExam.getId();
        //根据ID查询数量
        long count = interventionDao.findCountById(physicalExamId);
        if (count > 0) {
           throw new AssociatedException();
        }
        //根据膳食id查询要干预的膳食信息
        String foods = findFood(foodIds);
        //根据运动id查询要干预的运动信息
        String sports = findSport(sportIds);
        //调用dao
        interventionDao.add(physicalExamId, foods, sports);

    }

    //根据预约订单id查询健康干预
    @Override
    public Map findByOrderId(Integer orderId) {
        //根据预约订单id查询体检结果id
        Integer physicalexamId = interventionDao.findIdByOrderId(orderId);
        //根据体检结果id查询体检结果
        Map map = interventionDao.findById(physicalexamId);
        return map;
    }

    //遍历膳食id，根据膳食id查询对应的膳食名称、说明、食用尺寸
    public String findFood(Integer[] foodIds) {
        String foods = null;
        for (Integer foodId : foodIds) {
            //查询膳食信息
            foods = knowledgeFoodDao.findById(foodId) + ";";
        }
        return foods;
    }

    //遍历运动id，根据运动id查询对应的运动名称、次数、时间
    public String findSport(Integer[] sportIds) {
        String sports = null;
        for (Integer sportId : sportIds) {
            //查询膳食信息
            sports = knowledgeSportDao.findById(sportId) + ";";
        }
        return sports;
    }

}
